import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import * as compDiviService from '../../services/AccountDivi';
const daoName = "TUserDiviChange";
const ButtonGroup = Button.Group;
const columns = [
    { title: '转出员工', width: 120, sorter: true, key: 'EMID', caption: "User.Name", render: data => data.User.Name === "" ? "" : data.User.Name + "(" + data.User.No + ")", dispaly: true, filter: false },
    { title: '转出日期', width: 110, sorter: true, key: 'ZCDT', caption: "ZCDT", render: data => datetime.format(data.ZCDT, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '转出业绩', width: 200, sorter: true, key: 'ZCYJ', dataIndex: 'ZCYJCaptions', dispaly: true, filter: true },
    { title: '转入员工1', width: 120, sorter: true, key: 'EMID1', caption: "User1.Name", render: data => data.User1.Name === "" ? "" : data.User1.Name + "(" + data.User1.No + ")", dispaly: true, filter: false },
    { title: '占比1', width: 80, sorter: true, dataIndex: 'DSVL1', key: 'DSVL1', render: data => data * 100, dispaly: true, filter: false },
    { title: '转入员工2', width: 120, sorter: true, key: 'EMID2', caption: "User2.Name", render: data => data.User2.Name === "" ? "" : data.User2.Name + "(" + data.User2.No + ")", dispaly: true, filter: false },
    { title: '占比2', width: 80, sorter: true, dataIndex: 'DSVL2', key: 'DSVL2', render: data => (data === null || data === 0) ? "" : data * 100, dispaly: true, filter: false },
    { title: '转入员工3', width: 120, sorter: true, key: 'EMID3', caption: "User3.Name", render: data => data.User3.Name === "" ? "" : data.User3.Name + "(" + data.User3.No + ")", dispaly: true, filter: false },
    { title: '占比3', width: 80, sorter: true, dataIndex: 'DSVL3', key: 'DSVL3', render: data => (data === null || data === 0) ? "" : data * 100, dispaly: true, filter: false },
    { title: '转入员工4', width: 120, sorter: true, key: 'EMID4', caption: "User4.Name", render: data => data.User4.Name === "" ? "" : data.User4.Name + "(" + data.User4.No + ")", dispaly: true, filter: false },
    { title: '占比4', width: 80, sorter: true, dataIndex: 'DSVL4', key: 'DSVL4', render: data => (data === null || data === 0) ? "" : data * 100, dispaly: true, filter: false },
    { title: '转入员工5', width: 120, sorter: true, key: 'EMID5', caption: "User5.Name", render: data => data.User5.Name === "" ? "" : data.User5.Name + "(" + data.User5.No + ")", dispaly: true, filter: false },
    { title: '占比5', width: 80, sorter: true, dataIndex: 'DSVL5', key: 'DSVL5', render: data => (data === null || data === 0) ? "" : data * 100, dispaly: true, filter: false },
];
const controls = [
    {
        name: "EMID", label: "转出员工", type: "search", grid: 12 / 24, required: true,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "ZCDT", label: "转出日期", type: "date", grid: 12 / 24, dataType: "date", required: true },
    { name: "ZCYJ", label: "转出业绩", required: true, data: [{ value: '1', label: '对公帐户业绩' }, { value: '2', label: '对私帐户业绩' }], grid: 24 / 24, layout: { labelSpan: 3, wrapperSpan: 21 }, type: "checkbox-group" },

    {
        name: "EMID1", label: "转入员工", type: "search", grid: 12 / 24, required: false,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "DSVL1", label: '占比', type: "number", grid: 12 / 24, dataType: "number" },
    {
        name: "EMID2", label: "转入员工2", type: "search", grid: 12 / 24, required: false,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "DSVL2", label: '占比2', type: "number", grid: 12 / 24, dataType: "number" },
    {
        name: "EMID3", label: "转入员工3", type: "search", grid: 12 / 24, required: false,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "DSVL3", label: '占比3', type: "number", grid: 12 / 24, dataType: "number" },
    {
        name: "EMID4", label: '转入员工4', type: "search", grid: 12 / 24, multiple: false,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "DSVL4", label: '占比4', type: "number", grid: 12 / 24, dataType: "number" },
    {
        name: "EMID5", label: '转入员工5', type: "search", grid: 12 / 24, multiple: false,
        fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        dataType: "number", seekType: 2
    },
    { name: "DSVL5", label: '占比5', type: "number", grid: 12 / 24, dataType: "number" },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class UserDiviChangeFrom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            seachData: {}
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20 }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    edidOkHandler() {
        const form = this.refs.userDiviChangeFrom.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                //验证是否相对应的客户经理和分户比例都存在或者都不存在
                if ((values["EMID2"] === "" && values["DSVL2"] !== undefined && values["DSVL2"] !== 0) || (values["EMID2"] !== "" && values["DSVL2"] === undefined && values["DSVL2"] === 0)) {
                    message.error("转入员工2和对应的分户比例2必须都有或者都没有！")
                    return;
                }
                if ((values["EMID3"] === "" && values["DSVL3"] !== undefined) && values["DSVL3"] !== 0 || (values["EMID3"] !== "" && values["DSVL3"] === undefined && values["DSVL3"] === 0)) {
                    message.error("转入员工3和对应的分户比例3必须都有或者都没有！")
                    return;
                }
                if ((values["EMID4"] === "" && values["DSVL4"] !== undefined && values["DSVL4"] !== 0) || (values["EMID4"] !== "" && values["DSVL4"] === undefined && values["DSVL4"] === 0)) {
                    message.error("转入员工4和对应的分户比例4必须都有或者都没有！")
                    return;
                }
                if ((values["EMID5"] === "" && values["DSVL5"] !== undefined && values["DSVL5"] !== 0) || (values["EMID5"] !== "" && values["DSVL5"] === undefined && values["DSVL5"] === 0)) {
                    message.error("转入员工5和对应的分户比例5必须都有或者都没有！")
                    return;
                }
                //验证客户经理是否存在分配多次的情况
                if (values["EMID1"] === values["EMID2"] || values["EMID1"] === values["EMID3"] || values["EMID1"] === values["EMID4"] || values["EMID1"] === values["EMID5"]
                    || (values["EMID2"] === values["EMID3"] && (values["EMID2"] !== "" && values["EMID3"] !== ""))
                    || (values["EMID2"] === values["EMID4"] && (values["EMID2"] !== "" && values["EMID4"] !== ""))
                    || (values["EMID2"] === values["EMID5"] && (values["EMID2"] !== "" && values["EMID5"] !== ""))
                    || (values["EMID3"] === values["EMID4"] && (values["EMID4"] !== "" && values["EMID3"] !== ""))
                    || (values["EMID3"] === values["EMID5"] && (values["EMID5"] !== "" && values["EMID3"] !== ""))
                    || (values["EMID4"] === values["EMID5"] && (values["EMID4"] !== "" && values["EMID5"] !== ""))) {
                    message.error("转入员工不允许重复分配！")
                    return;
                }
                let t = `${daoName}/create`
                let msg = "数据添加成功！"
                controls.map((c, i) => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = values[c.name] === undefined ? 0 : Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        values[c.name] = !values[c.name] ? null : new Date(values[c.name])
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                if (values.EMID < 0 || values.EMID1 < 0 || values.EMID2 < 0 || values.EMID3 < 0 || values.EMID4 < 0 || values.EMID5 < 0) {
                    message.error('分配失败！转入或转出员工为虚拟员工，不支持业绩批量调整！请重新选择')
                    return;
                }
                //验证所有客户经理分户比例只和是否等于100%
                let sumDsvl = 0;
                sumDsvl = Number(values["DSVL1"]) + Number(values["DSVL2"]) + Number(values["DSVL3"]) + Number(values["DSVL4"]) + Number(values["DSVL5"])
                if (sumDsvl !== 100) {
                    message.error("所有转入员工分户比例总和必须等于100！")
                    return;
                }
                this.state.dataChange = true;
                let dataSource = []
                let data = {
                    EMID: values.EMID,
                    ZCDT: values.ZCDT,
                    ZCYJ: values.ZCYJ,
                    EMID1: values.EMID1,
                    DSVL1: Number(values.DSVL1) / 100,
                    EMID2: values.DSVL2 !== 0 ? values.EMID2 : null,
                    DSVL2: values.DSVL2 !== 0 ? Number(values.DSVL2) / 100 : null,
                    EMID3: values.DSVL3 !== 0 ? values.EMID3 : null,
                    DSVL3: values.DSVL3 !== 0 ? Number(values.DSVL3) / 100 : null,
                    EMID4: values.DSVL4 !== 0 ? values.EMID4 : null,
                    DSVL4: values.DSVL4 !== 0 ? Number(values.DSVL4) / 100 : null,
                    EMID5: values.DSVL5 !== 0 ? values.EMID5 : null,
                    DSVL5: values.DSVL5 !== 0 ? Number(values.DSVL5) / 100 : null,
                }
                dataSource.push(data)
                Modal.confirm({
                    title: '提示',
                    content: `你确认要对员工执行业绩转出操作吗？`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        compDiviService.UserDiviChange({ dataSource }
                        ).then(function (data) {
                            if (data === "OK") {
                                message.success("保存成功！")
                            } else {
                                message.error("业绩转移失败！" + data)
                            }
                        }).catch(function (ex) {
                            let errors = ex.toString().substring(ex.toString().indexOf("错误信息"), ex.toString().length)
                            message.error(errors)
                        });
                        this.props.dispatch({
                            type: `${daoName}/setRecord`,
                            payload: { record: {} },
                        });
                    }
                });
            }
        });
    };
    addHandler() {
        const form = this.refs.userDiviChangeFrom.getForm();
        form.resetFields();
        this.props.dispatch({
            type: `${daoName}/setRecord`,
            payload: { record: {} },
        });
    };
    hideEditHandler() {
        const form = this.refs.userDiviChangeFrom.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    seachHandler(data) {
        this.state.seachData = data;
    }
    render() {
        let { showEdit, record, permID, popedomTypes } = this.props
        let data = null
        let pTypes = popedomTypes[permID]
        if (pTypes.indexOf("2") !== -1) {
            data=<ButtonGroup style={{ zIndex: 0 }}>
                <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button>
            </ButtonGroup>
        }
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {data}
                    </div>
                    <Modal title="新增业绩转移" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>,
                        ]}
                    >
                        <EditFrom ref="userDiviChangeFrom" daoName={daoName} controls={controls} record={record} />
                    </Modal>
                    <DataTable ref="userDiviChangeTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record
    }
}
UserDiviChangeFrom = connect(mapStateToProps)(UserDiviChangeFrom)
export default UserDiviChangeFrom;

let render = (props) => React.createElement(UserDiviChangeFrom, props);
let f = new Factory()
f.set("UserDiviChangeFrom", render)
